package com.yanqu.road.server.manger.activity.doublespring;

import com.mysql.jdbc.log.Log;
import com.yanqu.road.dao.impl.activity.doublespring.DoubleSpringZlUserDataDaoImpl;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.UserActivityConditionData;
import com.yanqu.road.entity.activity.doublespring.DoubleSpringActivityConfig;
import com.yanqu.road.entity.activity.doublespring.data.DoubleSpringZlUserData;
import com.yanqu.road.entity.activity.doublespring.enums.DoubleSpringLogBeInviteTypeEnum;
import com.yanqu.road.entity.bag.UseGoodsResult;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.config.goods.OpenGoodsBagResult;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.log.doublespring.LogActivityDoubleSpringBeInvite;
import com.yanqu.road.entity.log.doublespring.LogActivityDoubleSpringTravelScore;
import com.yanqu.road.logic.bussiness.player.UserActivityBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.activity.DoubleSpringProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.doublespring.DoubleSpringActivityModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.PreReduceModule;
import com.yanqu.road.server.logic.bag.BaseUseGoods;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.CommonActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.config.GoodsBagMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigInteger;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class DoubleSpringActivityMgr extends TempMgr {

    private static Logger logger = LogManager.getLogger(CommonActivityMgr.class.getName());

    //活动配置
    static Map<Integer, DoubleSpringActivityConfig> activityConfigMap = new ConcurrentHashMap<>();

    @Override
    public boolean init() throws Exception {
        return true;
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    /**
     * 加载活动配置
     */
    public static void reloadActivityData() {
        getLogger().info("reload doubleSpring Activity start");
        //获取活动
        List<ActivityInfo> activityList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.DoubleSpring.getValue());
        Map<Integer, DoubleSpringActivityConfig> newActivityConfigMap = new ConcurrentHashMap<>();
        for (ActivityInfo activityInfo: activityList) {
            //获取config
            Map<String, ActivityConfig> configMap = NormalActivityMgr.getActivityConfigMap(activityInfo.getActivityId());
            //new DoubleSpringActivityConfig
            DoubleSpringActivityConfig doubleSpringActivityConfig = new DoubleSpringActivityConfig(activityInfo, configMap);
            newActivityConfigMap.put(activityInfo.getActivityId(), doubleSpringActivityConfig);
        }
        activityConfigMap = newActivityConfigMap;
        //同步一下在线玩家
        List<GamePlayer> playerList = GamePlayerMgr.getAllOnlinePlayer();
        for (GamePlayer gamePlayer : playerList) {
            gamePlayer.getModule(DoubleSpringActivityModule.class).syncMsg();
        }
        getLogger().info("reload doubleSpring Activity end");
    }

    /**
     * 获取活动配置
     * @param activityId
     * @return
     */
    public static DoubleSpringActivityConfig getActivityConfig(int activityId) {
        return activityConfigMap.get(activityId);
    }

//    /**
//     * 出行跨服返回处理
//     * @param gamePlayer
//     * @param activityId
//     * @param score
//     * @param partnerUserId
//     * @param addScore
//     * @return 出行操作获取的奖励
//     */
//    public static String travelCrossHandle(GamePlayer gamePlayer, int activityId, long score, long partnerUserId, long addScore) {
//        DoubleSpringActivityConfig config = getActivityConfig(activityId);
//        //消耗道具(开启连理果礼包)
//        String reward = "";
//        Property property = config.getDoubleSpringItemCost();
//        boolean costFlag = true;
//        for (Map.Entry<Integer, BigInteger> entry : property.getGoods().entrySet()) {
//            int goodsId = entry.getKey();
//            long costNum = entry.getValue().longValue();
//            GoodsInfo goodsInfo = GoodsMgr.getGoodsById(goodsId);
//            BaseUseGoods useGoodsEntity = BaseUseGoods.getUseGoodsEntity(gamePlayer, goodsInfo, 0, "");
//            if (useGoodsEntity != null) {
//                //使用掉
//                UseGoodsResult useGoodsResult = useGoodsEntity.useGoods(costNum);
//                if (useGoodsResult.getRet() == 0) {
//                    //消耗成功
//                    reward = useGoodsResult.getReward();
//                } else {
//                    costFlag = false;
//                }
//            }
//        }
//        //更新积分
//        if (costFlag) {
//            updateScore(gamePlayer.getUserId(), score, activityId, addScore, partnerUserId, true);
//        }
//        return reward;
//    }

    /**
     * 出行跨服返回处理
     * @param gamePlayer
     * @param activityId
     * @param score
     * @param partnerUserId
     * @param addScore
     * @return 出行操作获取的奖励
     */
    public static String travelCrossHandle(GamePlayer gamePlayer, int activityId, long score, long partnerUserId, long addScore) {
        DoubleSpringActivityConfig config = getActivityConfig(activityId);
        //消耗道具(开启连理果礼包)
        Property reward = new Property();
        Property property = config.getDoubleSpringItemCost();
        //remove掉
        boolean costFlag = gamePlayer.getModule(CurrencyModule.class).removeCurrency(property, eLogMoneyType.DoubleSpring, eLogMoneyType.DoubleSpringTravelCost);
        //获取礼包随机道具
        for (Map.Entry<Integer, BigInteger> entry : property.getGoods().entrySet()) {
            int goodsId = entry.getKey();
            long costNum = entry.getValue().longValue();
            for (int i = 0; i < costNum; i++) {
                OpenGoodsBagResult openGoodsBagResult = GoodsBagMgr.getRandomGoods(goodsId);
                reward.addProperty(openGoodsBagResult.getReward());
            }
        }
        //添加礼包道具
        gamePlayer.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.DoubleSpring, eLogMoneyType.DoubleSpringTravelReward);
        //更新积分
        if (costFlag) {
            updateScore(gamePlayer.getUserId(), score, activityId, addScore, partnerUserId, true);
        }
        return PropertyHelper.parsePropertyToString(reward);
    }

    /**
     * 积分变更
     * @param userId 玩家ID
     * @param score 总积分
     * @param activityId 活动ID
     * @param addScore 增加的积分
     * @param partnerUserId 伙伴ID
     * @param travelFlag 是否操作出行
     */
    public static void updateScore(long userId, long score, int activityId, long addScore, long partnerUserId, boolean travelFlag) {
        ActivityInfo activityInfo = ActivityMgr.getOpenActivityInfo(activityId);
        if (activityInfo == null) {
            return;
        }
        Object playerLock = GamePlayerMgr.getPlayerLock(userId);
        synchronized (playerLock) {
            GamePlayer gamePlayer = GamePlayerMgr.getOnlinePlayer(userId);
            //增加积分处理
            if (gamePlayer != null) {
                //更新积分
                gamePlayer.getModule(DoubleSpringActivityModule.class).updateTravelScore(activityId, score);
            } else {
                //玩家不在线
                long now = System.currentTimeMillis() / 1000;
                List<UserActivityConditionData> tmpConditionDataList = UserActivityBussiness.getUserActivityConditionDataListByUserIdAndType(activityId, userId, eGamePlayerEventType.DoubleSpringScore.getValue());
                for (UserActivityConditionData tmpConditionData : tmpConditionDataList) {
                    if (!tmpConditionData.isGetReward() && BigInteger.valueOf(score).compareTo(tmpConditionData.getValue()) > 0) {
                        tmpConditionData.setValue(BigInteger.valueOf(score));
                        tmpConditionData.setModifyTime(now);
                        // 更新condition
                        UserActivityBussiness.updateUserActivityConditionData(tmpConditionData);
                    }
                }
            }
        }
        logger.info("踏春游记-出行更新积分,userId:{}, activityId:{}, score:{}", userId, activityId, score);
        //日志
        LogActivityDoubleSpringTravelScore log = new LogActivityDoubleSpringTravelScore();
        log.setActivityId(activityId);
        log.setUserId(userId);
        log.setPartnerUserId(partnerUserId);
        if (travelFlag) {
            log.setSelfAddScore(addScore);
            log.setPartnerAddScore(0);
        } else {
            log.setSelfAddScore(0);
            log.setPartnerAddScore(addScore);
        }
        log.setAllAddScore(addScore);
        log.setTotalScore(score);
        log.setCreateTime(System.currentTimeMillis());
        AutoLogMgr.add(log);
    }

    /**
     * 成功组队
     * @param userId
     * @param reqMsg
     */
    public static void successTeam(long userId, DoubleSpringProto.DoubleSpringCrossTeamSuccessSyncMsg reqMsg) {
        ActivityInfo activityInfo = ActivityMgr.getOpenActivityInfo(reqMsg.getActivityId());
        if (activityInfo == null) {
            return;
        }
        //积分变更
        if (reqMsg.getAddScore() > 0) {
            updateScore(userId, reqMsg.getScore(), reqMsg.getActivityId(), reqMsg.getAddScore(), reqMsg.getPartnerUserId(), false);
            logger.info("踏春游记-组队后更新积分,userId:{}, activityId:{}, score:{}", userId, reqMsg.getActivityId(), reqMsg.getScore());
        }
        //日志
        if (reqMsg.getOperateFlag()) {
            LogActivityDoubleSpringBeInvite log = new LogActivityDoubleSpringBeInvite();
            log.setActivityId(activityInfo.getActivityId());
            log.setUserId(userId);
            log.setInviteUserId(reqMsg.getPartnerUserId());
            log.setType(DoubleSpringLogBeInviteTypeEnum.TYPE_AGREE_INVITE.getType());
            log.setCreateTime(System.currentTimeMillis());
            AutoLogMgr.add(log);
        }
    }

    public static boolean isDoubleSpringZhanLingItem(int goodsId){
        //热更先写死，后续在优化
        Set<Integer> goodsSet = new HashSet<>();
        goodsSet.add(101710);
        goodsSet.add(101889);
        if (goodsSet.contains(goodsId)) {
            List<ActivityInfo> activityList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.DoubleSpring.getValue());
            for (ActivityInfo activityInfo : activityList) {
                Map<String, ActivityConfig> activityConfigMap = NormalActivityMgr.getActivityConfigMap(activityInfo.getActivityId());
                ActivityConfig config = activityConfigMap.get("EXCHANGE_SCORE_ITEM_ID");
                if (config != null && config.getIntValue() == goodsId) {
                    return true;
                }
            }
        }
        return false;
//
//        for (DoubleSpringActivityConfig config:activityConfigMap.values()){
//            if (!ActivityMgr.activityInShowTime(config.getActivityInfo())){
//                continue;
//            }
//            if (config.getExchangeScoreItemId() == goodsId){
//                return true;
//            }
//        }
//        return false;
    }


}
